package com.defysoft.waukids.intro;

import java.util.ArrayList;
import java.util.Calendar;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukids.BaseActivity;
import com.defysoft.waukids.Data_Type.BC_SCHOOL;
import com.defysoft.waukids.Intro_Yacguan;
import com.defysoft.waukids.JsonParser;
import com.defysoft.waukids.R;

//회원가입.
public class Intro_Join_A extends BaseActivity implements OnClickListener {
	String uuid = "";
	EditText editText[] = new EditText[8];
	TextView textView[] = new TextView[3];
	ArrayList<String> addcode;
	ArrayList<String> addname;
	ArrayList<String> schoolname;
	ArrayList<BC_SCHOOL> schoollist;
	Button btn;
	RadioGroup radioGroup;
	RadioButton radioButton;
	String Mem_Rank, birth;
	InputMethodManager ipm;
	String address = "";// 입력된 동주소
	String addposition = "";// 선택된 주소
	String sch_code = "";

	private final int JOIN_THREAD = 1;
	private final int EMAIL_CHECK = 2;
	private final int ADD_CHECK = 3;
	private final int SELECT_SCHOOL = 4;
	private final int SUCCESS_SCHOOL = 5;
	private final int SUCCESS_ADD = 6;
	private final int FAIL_EMAIL_CHECK = 7;
	private final int SUCCESS_EMAIL_CHECK = 8;
	private final int FAIL_JOIN = 9;
	private final int SUCCESS_JOIN = 10;

	boolean emailcheck; // 아이디확인했는지 여부.
	Toolbar toolbar;
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == INTRO_YACGUAN_TO_JOIN_OK) {
			if (data.getStringExtra("yacguan").equals("ok")) {
				Toast.makeText(this, "약관에 동의하였습니다.", Toast.LENGTH_SHORT).show();
			} else if (data.getStringExtra("yacguan").equals("no")) {
				finish();
			}
		}
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		startActivityForResult(new Intent(Intro_Join_A.this, Intro_Yacguan.class), INTRO_JOIN_TO_YACGUAN);
		setContentView(R.layout.activity_intro__join_);
		setStartData();
		setStartToolbar();
	}

	@Override
	public void setStartData() {
		super.setStartData();
		uuid = getIntent().getStringExtra(INTENT_EXTRA_INTRO_UUID);
		if (uuid == null) {uuid = "";}
		emailcheck = false; // 이메일확인.
		ipm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); // 키보드
																			// 보이고안보이기
		editText[0] = (EditText) findViewById(R.id.INTRO_JOIN_EMAIL);
		editText[1] = (EditText) findViewById(R.id.INTRO_JOIN_PASS);
		editText[2] = (EditText) findViewById(R.id.INTRO_JOIN_PASSCHECK);
		editText[3] = (EditText) findViewById(R.id.INTRO_JOIN_MOBILE_1);
		editText[4] = (EditText) findViewById(R.id.INTRO_JOIN_MOBILE_2);
		editText[5] = (EditText) findViewById(R.id.INTRO_JOIN_MOBILE_3);
		editText[6] = (EditText) findViewById(R.id.INTRO_JOIN_NAME);
		editText[7] = (EditText) findViewById(R.id.INTRO_JOIN_SCHOOL_SEARCH);
		for (int i = 0; i < editText.length; i++) {
			editText[i].setOnClickListener(this);
		}
		textView[0] = (TextView) findViewById(R.id.INTRO_JOIN_EMAIL_CHECK);
		btn = (Button) findViewById(R.id.INTRO_JOIN_BTN);
		textView[2] = (TextView) findViewById(R.id.INTRO_JOIN_BIRTH);
		textView[0].setOnClickListener(this); // 아이디 중복체크 버튼.
		btn.setOnClickListener(this); // 가입하기 버튼.
		textView[2].setOnClickListener(this); // 생일검색.
		toolbar = (Toolbar) findViewById(R.id.INTRO_JOIN_TOOL);
		//라디오버튼 보이고 안보이고
		radioGroup = (RadioGroup) findViewById(R.id.INTRO_JOIN_RANK_RG);
		//아이디확인 후 다시 바꾸면 아이디 확인 다시.
		editText[0].addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,int after) {
			}
			@Override
			public void afterTextChanged(Editable s) {	//글자가 바뀔때 마다.
				if (emailcheck == true) {
					textView[0].setVisibility(View.VISIBLE);
					Toast.makeText(Intro_Join_A.this, "중복확인을 다시 해주세요.", Toast.LENGTH_SHORT).show();
					emailcheck = false;
				}
			}
		});
		editText[2].addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				final int ss = s.length();
				final String sss = s.toString();
				if (sss.equals(editText[1].getText().toString())) {
					Toast.makeText(Intro_Join_A.this, "비밀번호 확인이 일치합니다." , Toast.LENGTH_SHORT).show();
				} 
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,	int after) {	}
			@Override
			public void afterTextChanged(Editable s) {	}
		});
	}// end

	private void setStartToolbar() {
		toolbar.setNavigationOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	@Override
	protected void handlingMessage(Message _message) {
		super.handlingMessage(_message);
		switch (_message.what) {
		case CATCH_EXCEPTION: // thread 에러 메세지
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT).show();
			emailcheck = false;
			break;
		case SUCCESS_JOIN:
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			/*showPopup("가입성공", "가입시 입력한 메일주소로 인증확인 메일이 발송 되었습니다.\n인증 후 로그인 하세요.", 0);*/
			setResult(INTRO_JOIN_TO_LOGIN);
			finish();
			break;
		case FAIL_JOIN:
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT).show();
			emailcheck = false;
			break;
		// 이메일확인버튼 클릭시.
		case EMAIL_CHECK:
			startNetwork(EMAIL_CHECK);
			break;
		case SUCCESS_EMAIL_CHECK: // 이메일확인성공.
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			Toast.makeText(this, "사용가능한 아이디(이메일) 입니다.", Toast.LENGTH_SHORT).show();
			textView[0].setVisibility(View.INVISIBLE);
			emailcheck = true;
			break;
		case FAIL_EMAIL_CHECK: // 이메일확인실패.
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			Toast.makeText(this, "중복된 아이디(이메일) 입니다.", Toast.LENGTH_SHORT).show();
			emailcheck = false;
			break;
		case SUCCESS_ADD:
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}

			AlertDialog.Builder alert = new AlertDialog.Builder(this);

			alert.setTitle("주소선택");
			ListView listView = new ListView(this);

			ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
					android.R.layout.simple_list_item_1, addname);
			listView.setAdapter(dataAdapter);
			alert.setView(listView);

			final DialogInterface mPopupDlg = alert.show();
			listView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					// TODO Auto-generated method stub
					addposition = addcode.get(position);
					startNetwork(SELECT_SCHOOL);
					mPopupDlg.dismiss();
				}
			});
			break;
		case SUCCESS_SCHOOL:
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			schoolname = new ArrayList<String>();
			for (int i = 0; i < schoollist.size(); i++) {
				schoolname.add(schoollist.get(i).Sch_Name);
			}
			AlertDialog.Builder schoolalert = new AlertDialog.Builder(this);

			schoolalert.setTitle("원선택");
			ListView schoollistView = new ListView(this);

			ArrayAdapter<String> schooldataAdapter = new ArrayAdapter<String>(
					this, android.R.layout.simple_list_item_1, schoolname);
			schoollistView.setAdapter(schooldataAdapter);
			schoolalert.setView(schoollistView);

			final DialogInterface schoolmPopupDlg = schoolalert.show();
			schoollistView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					// TODO Auto-generated method stub
					editText[7].setText(schoollist.get(position).Sch_Name);
					sch_code = schoollist.get(position).PK_Sch_Code + "";
					schoolmPopupDlg.dismiss();
				}
			});
			break;
		}
	}

	@Override
	public void startThread(int choice) {
		super.startThread(choice);
		final int cho = choice;
		firstThread = new Thread(new Runnable() {
			@Override
			public void run() {
				switch (cho) {
				case JOIN_THREAD:
					joinThread();
					break;
				case EMAIL_CHECK:
					emailCheckThread();
					break;
				case ADD_CHECK:
					showAddress();
					break;
				case SELECT_SCHOOL:
					selectSchool();
					break;
				}
			}
			
		});
		firstThread.start();
		startDIal();
	}

	protected void joinThread() {

		try {
			String set = publicHttpCallback(HTTP_MEMBER_JOIN, "PK_Mem_Email="
					+ editText[0].getText().toString() + "&Mem_Pass="
					+ editText[1].getText().toString() + "&Mem_Birth="
					+ textView[2].getText().toString() + "&Mem_Phone="
					+ editText[3].getText().toString()
					+ editText[4].getText().toString()
					+ editText[5].getText().toString() + "&Mem_Name="
					+ editText[6].getText().toString() + "&Mem_Rank="
					+ Mem_Rank + "&Mem_Uuid=" + uuid + "&Mem_Sch=" + sch_code);
			JSONObject jsonObject = new JSONObject(set);
			if (jsonObject.getBoolean("success")) {
				onNetworkCallback(SUCCESS_JOIN, "");
			} else {
				onNetworkCallback(FAIL_JOIN, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, "main" + e.toString());
		}
		;
	}

	protected void emailCheckThread() {
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(
					HTTP_MEMBER_JOIN_EMAILCHECK, "PK_Mem_Email="
							+ editText[0].getText().toString()));
			if (jsonObject.getBoolean("success")) {
				onNetworkCallback(SUCCESS_EMAIL_CHECK, "");
			} else {
				onNetworkCallback(FAIL_EMAIL_CHECK,
						jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, "main" + e.toString());
		}
		;
	}

	protected void showAddress() {
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(
					HTTP_MEMBER_SELECT_ADDLIST, "name=" + address));
			if (jsonObject.getBoolean("success")) {
				addcode = new ArrayList<String>();
				addname = new ArrayList<String>();
				JSONArray ja = new JSONArray(jsonObject.getString("payload"));
				JSONObject jo;
				for (int i = 0; i < ja.length(); i++) {
					jo = ja.getJSONObject(i);
					addcode.add(jo.getString("PK_Add_Code"));
					addname.add(jo.getString("Add_Si") + " "
							+ jo.getString("Add_Gu") + " "
							+ jo.getString("Add_Dong") + " "
							+ jo.getString("Add_Ri"));

				}
				onNetworkCallback(SUCCESS_ADD, "");
			} else {
				onNetworkCallback(FAIL_JOIN, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, "main" + e.toString());
		}
		;
	}

	protected void selectSchool() {
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(
					HTTP_MEMBER_SELECT_SCHOOL, "position=" + addposition));
			if (jsonObject.getBoolean("success")) {
				schoollist = JsonParser.SelectSchool(jsonObject.getString("payload"));
				onNetworkCallback(SUCCESS_SCHOOL,
						jsonObject.getString("payload"));
			} else {
				onNetworkCallback(FAIL_JOIN, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, "main" + e.toString());
		}
		;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.INTRO_JOIN_EMAIL_CHECK: // 아이디 중복체크.
			String email = editText[0].getText().toString();
			if (editText[0].getText().toString().equals("")) {
				emailcheck = false;
				Toast.makeText(this, "아이디를 입력해 주세요", Toast.LENGTH_SHORT).show();
			} else if (!isEmailValid(email)) {
				Toast.makeText(this, "이메일형식에 맞지 않습니다", Toast.LENGTH_SHORT).show();
			} else {
				onNetworkCallback(EMAIL_CHECK, "");
			}
			break;
		case R.id.INTRO_JOIN_BTN: // 회원가입.
			for (int i = 0; i < editText.length; i++) {
				ipm.hideSoftInputFromWindow(editText[i].getWindowToken(), 0);
			}
			checkJoin();// 검색 후 가입.

			break;
		case R.id.INTRO_JOIN_BIRTH: // 생일검색.
			for (int i = 0; i < editText.length; i++) {
				ipm.hideSoftInputFromWindow(editText[i].getWindowToken(), 0);
			}
			DialogBirthPicker();
			break;
		case R.id.INTRO_JOIN_SCHOOL_SEARCH: //주소검색
			AlertDialog.Builder alert = new AlertDialog.Builder(this);

			alert.setTitle("동선택");
			alert.setMessage("읍,면,동,리의 단위로 입력해주세요");

			// Set an EditText view to get user input
			final EditText input = new EditText(this);
			alert.setView(input);

			alert.setPositiveButton("Ok",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							address = input.getText().toString();
							startNetwork(ADD_CHECK);
						}
					});

			alert.setNegativeButton("Cancel",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							// Canceled.
						}
					});

			alert.show();
			break;
		}
	}

	private void checkJoin() {
		int check = 0;
		String email = editText[0].getText().toString();
		if (editText[0].getText().toString().equals("")) {
			emailcheck = false;
			Toast.makeText(this, "아이디를 입력해 주세요", Toast.LENGTH_SHORT).show();
			check = 1;
		} else if (!isEmailValid(email)) {
			editText[0].setText("");
			editText[0].setHint("이메일 형식이 맞지 않습니다.");
			editText[0].setHintTextColor(Color.RED);
			check = 1;
		} else if (editText[1].getText().length() < 8
				|| editText[1].getText().length() > 15) {
			editText[1].setText("");
			editText[2].setText("");
			editText[1].setHint("패스워드를 8자~15자로 입력하세요.");
			editText[1].setHintTextColor(Color.RED);
			check = 1;
		} else if (editText[2].getText().toString().length() < 0) {
			editText[2].setHint("패스워드확인을 입력해주세요.");
			editText[2].setHintTextColor(Color.RED);
			check = 1;
		} else if (!editText[2].getText().toString()
				.equals(editText[1].getText().toString())) {
			editText[2].setText("");
			editText[2].setHint("패스워드체크가 일치하지 않습니다.");
			editText[2].setHintTextColor(Color.RED);
			check = 1;
		}/* else if (textView[2].getText().length() < 5) {
			textView[2].setHint("생년월일을 입력하세요.");
			textView[2].setHintTextColor(Color.RED);
			check = 1;
		} else if (editText[3].getText().toString().equals("")
				|| editText[4].getText().toString().equals("")
				|| editText[5].getText().toString().equals("")) {
			Toast.makeText(this, "폰번호를 입력하세요.", Toast.LENGTH_SHORT).show();
			editText[3].setHintTextColor(Color.RED);
			editText[4].setHintTextColor(Color.RED);
			editText[5].setHintTextColor(Color.RED);
			check = 1;
		}*/ else if (editText[6].getText().length() < 2) {
			editText[6].setHint("이름을 입력하세요.");
			editText[6].setHintTextColor(Color.RED);
			check = 1;
		} else if (editText[7].getText().length() <2) {
			editText[7].setHint("유치원을 선택하세요.");
			editText[7].setHintTextColor(Color.RED);
			check = 1;
		}
		////////////////////////////////
		
		
		//////////////////////////////
		if (check == 0) {
			radioButton = (RadioButton) findViewById(radioGroup
					.getCheckedRadioButtonId());
			String choice_rb = radioButton.getText().toString();
			if (choice_rb.equals("학부모")) {
				Mem_Rank = "3";
			} else if (choice_rb.equals("선생님")) {
				Mem_Rank = "2";
			} else if (choice_rb.equals("원장님")) {
				Mem_Rank = "0";
			} // 원장대기=0
			for (int i = 0; i < editText.length; i++) {
				editText[i].getText().toString();
			}
			if (!emailcheck) {
				Toast.makeText(Intro_Join_A.this, "아이디 중복확인을 해주세요.", Toast.LENGTH_SHORT).show();
			} else {
				startNetwork(JOIN_THREAD);
			}
		}
	}

	// 생일선택 다이얼로그
	private void DialogBirthPicker() {
		Calendar c = Calendar.getInstance();
		int cyear = c.get(Calendar.YEAR);
		int cmonth = c.get(Calendar.MONTH);
		int cday = c.get(Calendar.DAY_OF_MONTH);

		DatePickerDialog.OnDateSetListener mDateSetListener = new OnDateSetListener() {
			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear,
					int dayOfMonth) {
				String month = (monthOfYear + 1) + "";
				if (month.length() == 1) {
					month = "0" + month;
				}
				birth = year + "" + month + "" + dayOfMonth;
				textView[2].setText(birth);
				textView[2].setTextColor(Color.BLACK);
			}
		};
		new DatePickerDialog(this, mDateSetListener, cyear, cmonth, cday)
				.show();
	}

	boolean isEmailValid(CharSequence email) { // 이메일 체크.
		return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
	}


}// CLASS_END
